package dao.impl;

import java.util.ArrayList;

import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import view.component.basecomponent.pojo.ComponentPojo;
import dao.IComponentDAO;

public class ComponentDAO implements IComponentDAO {

	private HibernateBase hibernateBase;

	public ComponentDAO() {
		hibernateBase = HibernateBase.getInstance();
	}

	@Override
	public void init() {
		hibernateBase.init();

	}

	@Override
	public void close() {
		hibernateBase.close();

	}

	@Override
	public boolean create(ComponentPojo component) {
		boolean status = false;

		EntityTransaction tx = hibernateBase.getManager().getTransaction();
		try {
			tx.begin();
			hibernateBase.getManager().persist(component);
			tx.commit();
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
			if (tx.isActive()) {
				tx.rollback();
			}
		}
		return status;
	}

	@Override
	public boolean update(ComponentPojo component) {
		boolean status = false;

		EntityTransaction tx = hibernateBase.getManager().getTransaction();
		try {
			tx.begin();
			hibernateBase.getManager().merge(component);
			tx.commit();
			status = true;
		} catch (Exception e) {
			e.printStackTrace();
			if (tx.isActive()) {
				tx.rollback();
			}
		}
		return status;
	}

	@Override
	public ComponentPojo getBy(long id) {
		ComponentPojo pojo = hibernateBase.getManager().find(
				ComponentPojo.class, id);
		return pojo;
	}

	@Override
	public boolean delete(ComponentPojo component) {
		boolean status = false;
		EntityTransaction tx = hibernateBase.getManager().getTransaction();
		try {
			tx.begin();
			hibernateBase.getManager().remove(component);
			tx.commit();

			status = true;
		} catch (Exception e) {
			e.printStackTrace();
			if (tx.isActive()) {
				tx.rollback();
			}
		}

		return status;
	}

	@SuppressWarnings("unchecked")
	public ArrayList<ComponentPojo> getAll() {
		String queryString = "SELECT cp FROM ComponentPojo cp";

		Query query = hibernateBase.getManager().createQuery(queryString);
		ArrayList<ComponentPojo> components = (ArrayList<ComponentPojo>) query
				.getResultList();

		return components;
	}

}
